package com.danskin.wechat.web;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.util.StringUtil;
import com.danskin.wechat.entity.CustInfo;
import com.danskin.wechat.model.LoginUser;
import com.danskin.wechat.service.StoreInfoService;
import com.danskin.wechat.util.DateTools;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.ExcelUtil;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.LogUtil;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.vo.StoreQrcodeScanVo;

import jxl.write.WritableWorkbook;

/**
 * 店铺二维码扫描类
 * 
 * @author makunsmac
 *
 */
@Controller
@RequestMapping("storeQrcodeScan")
public class StoreQrcodeScanController extends BaseController {

	@Autowired
	private StoreInfoService storeService;

	/**
	 * 跳转到店铺二维码扫描列表
	 * 
	 * @return
	 * @author makunsmac
	 */
	@RequestMapping(value = "jumpScanList", method = RequestMethod.GET)
	public String jumpScanList(Model model) {
		List<String> storeCodeList = new ArrayList<String>();

		try {
			// 去重查询所有店铺编号
			//storeCodeList = storeService.selectStoreCodeList();
		} catch (Exception e) {
			LogUtil.error("=======去重查询所有的店铺编号异常", e);
		}
		model.addAttribute("storeCodeList", storeCodeList);
		return "store/store_qrcode_scan_list";
	}
	@RequestMapping(value = "/checkExportStoreQrcode", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkExportStoreQrcode(String storeCode,String eventType,String startTime,String endTime) throws Exception {
		Map<String,Object> map=new HashMap<String, Object>();
    	String mpId = String.valueOf(this.getMpId());
    	List<StoreQrcodeScanVo> storeQrcodeScanVo = storeService.queryStoreQrcodeScanVoExport(storeCode,eventType,startTime,endTime,mpId);
    	if(storeQrcodeScanVo.size()>=30000){	
    		map.put("status", 400);
    		map.put("msg", "导出数据超过3W条，请缩小日期范围");
    	}else{
    		map.put("status", 200);
    		map.put("msg", "可以导出");
    	}
    	return JsonUtils.objectToJson(map);
	}
	/**
	 * 分页查询电频二维码扫描记录
	 * 
	 * @param page
	 * @return
	 * @author makunsmac
	 */
	@ResponseBody
	@RequestMapping(value = "queryScanList", method = RequestMethod.GET)
	public Object queryScanList(Page page) {
		List<StoreQrcodeScanVo> scanList = new ArrayList<StoreQrcodeScanVo>();
		try {
			Map map = getRequestParameter(getRequest());
			LoginUser loginUser = getLoginUser();
			map.put("mpId", loginUser.getMpId());
			page.setMap(map);
			scanList = storeService.listPageStoreQrcodeScan(page);

		} catch (Exception e) {
			LogUtil.error("=======分页查询电频二维码扫描记录异常", e);
		}
		return pagelistToJSONForBootStrapTable(scanList, page);
	}

	/**
	 * 根据查询条件导出店铺二维码扫描记录excel
	 * 
	 * @param storeCode
	 * @param eventType
	 * @param paramStartTime
	 * @param paramEndTime
	 * @author makunsmac
	 */
	@RequestMapping(value = "exportExcel", method = RequestMethod.GET)
	public void exportExcel(@RequestParam("storeCode") String storeCode, @RequestParam("eventType") Integer eventType,
			@RequestParam("paramStartTime") String paramStartTime, @RequestParam("paramEndTime") String paramEndTime, HttpServletResponse response) {
		OutputStream out = null;
		
		WritableWorkbook exportExcelWorkBook = null;
		
		if (eventType != null) {
			LogUtil.info("=======导出店铺二维码扫描记录参数：storeCode=" + storeCode + "&eventType=" + eventType + "&paramStartTime="
					+ paramStartTime + "&paramEndTime=" + paramEndTime);
		} else {
			LogUtil.info("=======导出店铺二维码扫描记录参数：storeCode=" + storeCode + "&paramStartTime=" + paramStartTime
					+ "&paramEndTime=" + paramEndTime);
		}
		
		try {
			out = response.getOutputStream();
			
			//封装查询参数
			StoreQrcodeScanVo param = new StoreQrcodeScanVo();
			param.setStoreCode(storeCode);
			param.setEventType(eventType);
			if(StringUtils.isNotBlank(paramStartTime)) {
				param.setParamStartTime(paramStartTime+ " " + "00:00:01");
			}else{
				param.setParamStartTime(DateUtils.getStartTime() + " " + "00:00:01");
			}
			if(StringUtils.isNotBlank(paramEndTime)) {
				param.setParamEndTime(paramEndTime+ " " + "23:59:59");
			}else{
				param.setParamEndTime(DateUtils.getEndTime() + " " + "23:59:59");
			}
			
			//查询符合条件的数据
			List<StoreQrcodeScanVo> scanList = storeService.selectStoreQrcodeScanList(param);
			
			//循环赋值eventTypeString
			if(CollectionUtils.isNotEmpty(scanList)) {
				for(StoreQrcodeScanVo temp : scanList) {
					if(temp.getEventType() == 0)	 {							//关注
						temp.setEventTypeString("关注");
					} else if(temp.getEventType() == 1) {					//扫描
						temp.setEventTypeString("扫描");
					}
				}
			}
			
			//封装表头
			LinkedHashMap<String, String> fieldMap = new LinkedHashMap<String, String>();
			fieldMap = packageExcelHead(fieldMap);
			
			//执行导出
			exportExcelWorkBook = ExcelUtil.listToExcel(scanList, fieldMap, "店铺二维码扫描记录", out);
			
			String fileName = "店铺二维码扫描记录-"+new SimpleDateFormat(DateTools.YYYYMMDDHHMMSS).format(new Date())+".xls";// 文件名        
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8"); 
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"), "iso8859-1"));
            exportExcelWorkBook.write();
            exportExcelWorkBook.close();
		} catch (Exception e) {
			LogUtil.error("======");
		} finally {
			try {
                if (out != null) {
                	out.close();
                }
            } catch (Exception ex) {
                LogUtil.error("======导出店铺二维码扫描记录流关闭失败", ex);
            }
		}
		
	}
	
	/**
	 * 封装表头
	 * @param fieldMap
	 * @return
	 * @author makunsmac
	 */
	private LinkedHashMap<String, String> packageExcelHead(LinkedHashMap<String, String> fieldMap) {
		fieldMap.put("storeCode", "门店编号");
        fieldMap.put("district", "区域");
        fieldMap.put("city", "城市");
        fieldMap.put("storeName", "店铺名称");
        fieldMap.put("eventTypeString", "动作");
        fieldMap.put("scanTime", "扫描时间");
        /*fieldMap.put("telephone", "顾客电话");
        fieldMap.put("contact", "顾客姓名");*/        
        return fieldMap;
	}
}
